package bidirectionallist;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:墨琦
 * Data:2023-04-10
 * Time:19:28
 */
public class List {

    static class Mylist{
        int data;
        Mylist next;
        Mylist prv;
        Mylist()
        {}
        Mylist(int sum)
        {
            data=sum;
        }
    }
    public Mylist head;
    public Mylist last;
    //算长度
    public int sizes(Mylist head)
    {
        Mylist cur=head;
        int size=0;
        while(cur!=null)
        {
            cur=cur.next;
            size++;
        }
        return size;
    }
    //头插
    public void addhead(int sum)
    {
        Mylist newhead=new Mylist(sum);
        if(head==null)
        {
            head=newhead;
            last=newhead;
        }
        else{
            newhead.next=head;
            head.prv=newhead;
            head=newhead;
        }

    }
    //尾插
    public void addtail(int sum)
    {
        if(head==null)
        {
            head.data=sum;
           last=head;
        }
        Mylist newhead=new Mylist(sum);
         last.next=newhead;
         newhead.prv=last;
         last=newhead;
    }
    //展示
    public void show()
    {
        Mylist kk=head;
        while(kk!=null)
        {
            System.out.print(kk.data+" ");
            kk=kk.next;
        }
    }
    //倒数第sum个节点
    public List.Mylist reciprocalNode(int sum)
    {

        Mylist kk=last;
        while(sum>1)
        {
            kk=kk.prv;
            sum--;
        }
        return kk;
    }
    //删除第i个结点
    public void delet(int sum)
    {
        Mylist fw=head;
        if(sum>new List().sizes(fw)||sum<=0)
        {
            return;
        }
        //删除头结点
        if(sum==1)
        {
            if(fw==null)
            {   return; }
            head=head.next;
            head.prv=null;
            fw.next=null;
            return ;
        }
        while(sum>1)
        {
            if(fw!=null) {
                fw = fw.next;
                sum--;
            }
        }
        //如果是尾结点
        if(fw.next==null)
        {
            fw=fw.prv;
            last.prv.next=null;
            last.prv=null;
            last=fw;
        }
        else {
            Mylist fw1 = fw.prv;
            fw1.next = fw.next;
            fw.next.prv = fw1;
            fw = null;
        }
    }

}
